/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package sv.com.globalsolutionslt.controlador;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.jasypt.util.password.BasicPasswordEncryptor;
import sv.com.globalsolutionslt.entidades.Usuario;

/**
 *
 * @author karinaMelara
 */
@Stateless
public class UsuarioFacade extends AbstractFacade<Usuario> {

    @PersistenceContext(unitName = "BoldeDeTrabajoPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public UsuarioFacade() {
        super(Usuario.class);
    }

    public Usuario validarAcceso(String usuario, String contrasenia) {
        try{
            String sql = "SELECT u FROM Usuario u  WHERE u.usuario='" + usuario + "'";
            System.out.println("Query ----- " + sql);
            Query q = em.createQuery(sql);
            Usuario usu = (Usuario) q.getSingleResult();

            if (usu != null) {
                BasicPasswordEncryptor encryptor = new BasicPasswordEncryptor();
                if (encryptor.checkPassword(contrasenia, usu.getContrasenia())) {
                    System.out.println("Bienvenido");
                    return usu;
                } else {
                    System.out.println("Error contrasenia no coincide");
                }
            }
            return null;
        }catch(NoResultException ne){
            System.out.println("Usuario o contraseña invalidos");
            return null;
        }catch(Exception e){
            throw e;
        }
    }

}
